package Utils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    /**
     * 文件的读取只需要读取一次即可，使用静态代码块
     */
    static {
        //读取资源文件，获取值
        try {
            Properties properties = new Properties();
            ClassLoader loader = JDBCUtil.class.getClassLoader();
            URL resource = loader.getResource("jdbc.properties");
            String path = resource.getPath();
            properties.load(new FileReader(path));

            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");

            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取连接
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }


    /**
     * 释放资源
     * @param stmt
     * @param coon
     */
    public static void close(Statement stmt, Connection coon){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (coon!=null){
            try {
                coon.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 释放资源
     * @param rs
     * @param stmt
     * @param coon
     */
    public static void close(ResultSet rs, Statement stmt, Connection coon){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (coon!=null){
            try {
                coon.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
